﻿function PictureViewModel() {
    var pictureVM =
    {
        Picture: ko.observable()
        , Visit: ko.observable()
        , PictureID: ko.observable()
        , VisitID: ko.observable()
        , PictureTypeID: ko.observable()
        , Title: ko.observable()
        , Url: ko.observable()
        , Rank: ko.observable()
        , IsDeleted: ko.observable(false)

        , PictureTypes: ko.observableArray(
            [new PictureType(1, "Photo")
            , new PictureType(2, "Panoramique")])

        , SelectedPictureType: ko.observable()

        , Load: function (visit, picture) {
            this.Visit(visit);

            if (picture != null) {
                this.Picture(picture);
                this.PictureID(picture.PictureID);
                this.VisitID(picture.VisitID);
                this.PictureTypeID(picture.PictureTypeID);
                this.Title(picture.Title);
                this.Url(picture.Url);
                this.Rank(picture.Rank);
            }

            for (var i = 0; i < this.PictureTypes().length; i++) {
                if (this.PictureTypes()[i].Id == this.PictureTypeID()) {
                    this.SelectedPictureType(this.PictureTypes()[i]);
                }
            }
        }

        /// <summary>
        /// Convert PictureViewModel object into Picture.
        /// </summary>
        , Unload: function () {
            var serverPicture = new mal.balades.Business.DataModel.Picture();

            serverPicture.PictureID = this.PictureID();
            serverPicture.VisitID = this.VisitID();
            serverPicture.PictureTypeID = this.PictureTypeID();
            serverPicture.Title = this.Title();
            serverPicture.Url = this.Url();
            serverPicture.Rank= this.Rank();

            return serverPicture;
        }

        , Delete: function () {
            this.IsDeleted(true);
        }
    };

    pictureVM.IsDirty = ko.dependentObservable(function () {
        if (this.Picture() != null) {
            if (this.Picture().Title != this.Title()
                || this.Picture().Url != this.Url()
                || this.Picture().Rank != this.Rank()
                || this.Picture().PictureTypeID != this.PictureTypeID())
                return true;
        }

        return false;
    }, pictureVM);

    pictureVM.SelectedPictureTypeChanged = ko.dependentObservable(function () {
        if (this.SelectedPictureType() != null) {
            this.PictureTypeID(this.SelectedPictureType().Id);
        }
    }, pictureVM);


    return pictureVM;
}

function PictureType(id, name) {
    this.Id = id;
    this.Name = name;
}